<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/7/24
 * Time: 11:45 AM
 */

namespace App\Services;

use App\Models\WechatDepartment;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;

class CustomerLinkService
{

    /**
     * 获取获客链接列表
     *
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLinkList($params)
    {
        $corpId     = $params['corp_id'] ?? '';
        $nextCursor = $params['next_cursor'] ?? '';
        $limit      = $params['limit'] ?? 100;

        try {
            $client   = new Client();
            $service  = new KfAccountService();
            $bodyData = [
                'limit'  => $limit,
            ];
            if ($nextCursor) {
                $bodyData['cursor'] = $nextCursor;
            }
            $body     = [
                'headers'            => $service->headers,
                RequestOptions::JSON => $bodyData
            ];
            $token    = $service->getReplaceAccessToken($corpId);
            $response = $client->request(
                'POST',
                sprintf($service->api['customer_link_list'], $token),
                $body
            );
            if ($response->getStatusCode() != 200) {

                return [];
            }
            $contents = $response->getBody()->getContents();
            Log::info('获取获客链接列表：', [$contents]);
            $data = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                return [];
            }
            if (!$linkList = $data['link_id_list'] ?? []) {

                return [];
            }
            Log::info('获取获客链接列表：', [$data]);
            $result = [
                'next_cursor' => $data['next_cursor'] ?? '',
                'list'        => []
            ];
            foreach ($linkList as $item) {
                $res = $client->request(
                    'POST',
                    sprintf($service->api['customer_link_detail'], $token),
                    [
                        'headers'            => $service->headers,
                        RequestOptions::JSON => [
                            'link_id' => $item ?? ''
                        ]
                    ]
                );
                if ($res->getStatusCode() != 200) {
                    continue;
                }
                $con      = $res->getBody()->getContents();
                $itemData = json_decode($con, true);
                if ($itemData['errcode'] != 0) {
                    continue;
                }
                array_push($result['list'], [
                    'link_id'       => $item,
                    'link_name'     => $itemData['link']['link_name'] ?? '',
                    'url'           => $itemData['link']['url'] ?? '',
                    'create_time'   => date('Y-m-d H:i:s', $itemData['link']['create_time'] ?? ''),
                ]);
            }

            return $result;
        } catch (\Exception $exception) {
            Log::error('获取获客链接列表失败：' . $exception->getMessage());

            return [];
        }
    }


    /**
     * 创建获客链接
     *
     * @param $params
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function createLink($params)
    {
        try {
            $corpId   = $params['corp_id'] ?? '';
            $linkName = $params['link_name'] ?? '';

            $departmentIds = WechatDepartment::query()
                ->where('corp_id', $corpId)
                ->where('parent_id', 0)
                ->pluck('department_id')
                ->toArray();

            $client   = new Client();
            $service  = new KfAccountService();
            $body     = [
                'headers'            => $service->headers,
                RequestOptions::JSON => [
                    'link_name' => $linkName,
                    'range'     => [
                        'department_list' => $departmentIds
                    ]
                ]
            ];
            $response = $client->request(
                'POST',
                sprintf($service->api['customer_link_create'], $service->getReplaceAccessToken($corpId)),
                $body
            );
            if ($response->getStatusCode() != 200) {
                throw new \Exception('请求失败！');
            }
            $contents = $response->getBody()->getContents();
            Log::info('创建获客链接：', [$contents, $body]);
            $data = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                throw new \Exception($data['errmsg'] ?? '创建失败');
            }

            return true;
        } catch (\Exception $exception) {
            Log::error('创建获客链接失败：' . $exception->getMessage());

            return $exception->getMessage();
        }
    }


    /**
     * 删除获客链接
     *
     * @param $params
     * @return bool|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deleteLink($params)
    {
        try {
            $corpId   = $params['corp_id'] ?? '';
            $linkId = $params['link_id'] ?? '';

            $client   = new Client();
            $service  = new KfAccountService();
            $body     = [
                'headers'            => $service->headers,
                RequestOptions::JSON => [
                    'link_id' => $linkId,
                ]
            ];
            $response = $client->request(
                'POST',
                sprintf($service->api['customer_link_delete'], $service->getReplaceAccessToken($corpId)),
                $body
            );
            if ($response->getStatusCode() != 200) {
                throw new \Exception('请求失败！');
            }
            $contents = $response->getBody()->getContents();
            Log::info('删除获客链接：', [$contents, $body]);
            $data = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                throw new \Exception($data['errmsg'] ?? '删除失败');
            }

            return true;
        } catch (\Exception $exception) {
            Log::error('删除获客链接失败：' . $exception->getMessage());

            return $exception->getMessage();
        }
    }


    /**
     * 获取获客链接额度
     *
     * @param $corpId
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getQuota($corpId)
    {
        try {
            $client   = new Client();
            $service  = new KfAccountService();
            $response = $client->request(
                'GET',
                sprintf($service->api['customer_link_quota'], $service->getReplaceAccessToken($corpId)),
                );
            if ($response->getStatusCode() != 200) {
                throw new \Exception('请求失败！');
            }
            $contents = $response->getBody()->getContents();
            $data     = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                throw new \Exception($data['errmsg'] ?? '获取失败');
            }

            foreach ($data['quota_list'] ?? [] as &$item) {
                $item['expire_date'] = date('Y-m-d', $item['expire_date']);
            }

            return [
                'total'      => $data['total'] ?? 0,
                'balance'    => $data['balance'] ?? '',
                'quota_list' => $data['quota_list'] ?? []
            ];
        } catch (\Exception $exception) {
            Log::error('获取获客链接额度失败：' . $exception->getMessage());

            return [];
        }
    }
}
